package com.base.cn.platform.os.common.utils.web.thirdLogin;

import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.http.HttpUtil;
import com.base.cn.platform.os.common.utils.user.ProfileType;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录工具类
 *
 * @author s.li
 * @date 2018/11/01
 */
public class WXLoginUtils {
    private static Gson gson = new Gson();
    /**
     * 获取微信登录的数据Map
     * @param openId
     * @param accessToken
     * @return Map<String,Object>
     * @throws Exception
     */
    public static Map<String,Object> getWxUserProfile(String openId,String accessToken) throws Exception{
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken+"&openid=" + openId;
        //获取返回数据
        JSONObject userInfoMap = urlWeiXinHalder(infoUrl);
        String photo = userInfoMap.get("headimgurl").toString();
        String cusName = userInfoMap.get("nickname").toString();
        String unionid = userInfoMap.get("unionid").toString();
        ////保存第三方登录数据
        Map<String,Object> userProfile = UserProfileUtils.genUserProfileMap(unionid, ProfileType.WEIXIN.toString(),photo,cusName);
        return userProfile;
    }

    /**
     * 获取微信的openId 和 accessToken
     * @param appId 应用的AppID
     * @param appSecret
     * @param code
     * @return Map<String,String>
     * @throws Exception
     */
    public static Map<String,String> getAccessTokenAndOpendId (String appId,String appSecret,String code) throws Exception{
        //拼写微信获取access_token访问地址
        String getAccessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        getAccessUrl += "?appid=" + appId+"&secret=" + appSecret+"&code=" + code+"&grant_type=authorization_code";
        JSONObject userMap = urlWeiXinHalder(getAccessUrl);
        String openId = userMap.get("openid").toString();
        String accessToken = userMap.get("access_token").toString();
        Map<String,String> map = new HashMap<>();
        map.put("openId",openId);
        map.put("accessToken",accessToken);
        return map;
    }

    /**
     * 处理微信访问的url
     * @param url
     * @return
     * @throws Exception
     */
    public static JSONObject urlWeiXinHalder(String url) throws Exception {
        //请求访问
        String result = HttpUtil.doGet(url);
        JSONObject jsonObject = new JSONObject(result);
        return jsonObject;
    }

    /**
     * 获取微信公众号的 accessToken
     * @param appId 公众号ApppId
     * @param appSecret 公众号appSecret
     * @param customCacheChannel
     * @return accessToken
     */
    public static String getOpenAccessToken(String appId, String appSecret, CustomCacheChannel customCacheChannel) throws IOException {
        String accessToken = (String)customCacheChannel.get(J2CacheRegion.TWO_HOURS_REGION.getKey(),"public_wx_access_token").getValue();
        if(!StringUtils.isNotEmpty(accessToken)){
            accessToken = getAccessToken(appId, appSecret);
            customCacheChannel.set(J2CacheRegion.TWO_HOURS_REGION.getKey(),"public_wx_access_token",accessToken);
        }
        return accessToken;
    }

    /**
     * 获取微信小程序的 accessToken
     * @param appId 小程序ApppId
     * @param appSecret 小程序appSecret
     * @param customCacheChannel
     * @return accessToken
     */
    public static String getMiniAccessToken(String appId, String appSecret, CustomCacheChannel customCacheChannel) throws IOException {
        String accessToken = (String)customCacheChannel.get(J2CacheRegion.TWO_HOURS_REGION.getKey(),"mini_wx_access_token").getValue();
        if(!StringUtils.isNotEmpty(accessToken)){
            accessToken = getAccessToken(appId, appSecret);
            customCacheChannel.set(J2CacheRegion.TWO_HOURS_REGION.getKey(),"mini_wx_access_token",accessToken);
        }
        return accessToken;
    }

    private static String getAccessToken(String appId, String appSecret) throws IOException{
        // 获取公众号access_token的链接
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
        //获取getAccessToken
        String result = HttpUtil.doPost(requestUrl, null);
        Map<String, String> map = gson.fromJson(result, new TypeToken<Map<String, String>>() {}.getType());
        // 如果请求成功
        if (!map.isEmpty()) {
            String errcode = map.get("errcode");
            if(StringUtils.isEmpty(errcode)){
                String access_token = map.get("access_token");
                return access_token;
            }
        }
        return null;
    }
}
